package com.tbit.uqbike.client.remote.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tbit.uqbike.client.util.HttpClientUtils;
import com.tbit.uqbike.client.util.LogUtil;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.*;


/**
 * @Author: chen
 * @Description: 创蓝智云短信实名工具类
 * @Date: 创建于 15:31 2021/6/18
 */
@Slf4j
public class ClzySmsAuthUtil {

    /**
     * 实名认证签名校验地址
     */
    private static String URLV2 = "https://api.253.com/open/idcard/id-card-auth/vs";
    /**
     * 实名认证普通地址
     */
    private static String URL = "https://api.253.com/open/idcard/id-card-auth";

    /**
     * 国内短信发送
     *
     * @param account  用户名
     * @param password 密码
     * @param msg      短信内容 模板需要完整内容配置，签名需要申请
     * @param phone    手机号码，多个用英文逗号分割
     * @return
     */
    public static boolean sendSms(String account, String password, String msg, String phone) {
        String url = "http://smssh1.253.com/msg/v1/send/json";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account", account);
        jsonObject.put("password", password);
        jsonObject.put("msg", msg);
        jsonObject.put("phone", phone);
        String json = jsonObject.toJSONString();
        try {
            String tmp = HttpClientUtils.httpJson(url, json);
            LogUtil.info("创蓝短信发送返回=" + tmp);
            JSONObject jsonObject1 = JSON.parseObject(tmp);
            String errcode = jsonObject1.getString("code");
            if ("0".equals(errcode)) {
                return true;
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 实名认证
     *
     * @param appId  appId
     * @param appKey appKey
     * @param name   用户名
     * @param idNO   身份证号码
     * @return
     */
    public static boolean nameAuth(String appId, String appKey, String name, String idNO) {
        String url = URL;
        Map<String, String> params = new HashMap<String, String>();
        params.put("appId", appId);
        params.put("appKey", appKey);
        params.put("name", name);
        params.put("idNum", idNO);
        try {
            String result = HttpClientUtils.httpPost(url, params);
            System.out.println(result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String code = jsonObject.getString("code");
            if ("200000".equals(code)) {
                JSONObject data = jsonObject.getJSONObject("data");
                String tmp = data.getString("result");
                if ("01".equals(tmp)) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
        return false;
    }

    /**
     * 实名认证签名加密校验版
     *
     * @param appId
     * @param appKey
     * @param name
     * @param idNO
     * @return
     */
    public static boolean nameAuthBySign(String appId, String appKey, String name, String idNO) {
        String url = URLV2;
        Map<String, Object> requestMap = getPostData(appId, name, idNO);
        String requestStr = requestMap2Str(requestMap);
        String sign = hmacSHA1Encrypt(requestStr, appKey);////生成的签名字符串
        System.out.println("签名：" + sign);
        Map<String, String> params = new HashMap<String, String>();
        params.put("appId", appId);
        params.put("sign", sign);
        params.put("idNum", idNO);
        params.put("name", name);
        try {
            String result = HttpClientUtils.httpPost(url, params);
            System.out.println(result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String code = jsonObject.getString("code");
            if ("200000".equals(code)) {
                JSONObject data = jsonObject.getJSONObject("data");
                String tmp = data.getString("result");
                if ("01".equals(tmp)) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
        return false;
    }


    /**
     * 生成加密字符串
     *
     * @param requestMap
     * @return
     */
    private static String requestMap2Str(Map<String, Object> requestMap) {
        List<String> list = new ArrayList<>(requestMap.keySet());
        Collections.sort(list);
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : list) {
            stringBuilder.append(key).append(requestMap.get(key));
        }
        return stringBuilder.toString();
    }

    /**
     * 使用这个三个字段进行加密验签
     *
     * @param appId
     * @param name
     * @param idNum
     * @return
     */
    private static Map<String, Object> getPostData(String appId, String name, String idNum) {
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("idNum", idNum);
        requestMap.put("name", name);
        requestMap.put("appId", appId);
        return requestMap;
    }

    /**
     * 生成加密字符串,并用Base64进行编码
     *
     * @param encryptText
     * @param encryptKey
     * @return
     */
    public static String hmacSHA1Encrypt(String encryptText, String encryptKey) {
        byte[] result = null;
        try {
            //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
            SecretKeySpec signinKey = new SecretKeySpec(encryptKey.getBytes("UTF-8"), "HmacSHA1");
            //生成一个指定 Mac 算法 的 Mac 对象
            Mac mac = Mac.getInstance("HmacSHA1");
            //用给定密钥初始化 Mac 对象
            mac.init(signinKey);
            //完成 Mac 操作
            byte[] rawHmac = mac.doFinal(encryptText.getBytes("UTF-8"));
            result = Base64.getEncoder().encode(rawHmac);

        } catch (Exception e) {

        }
        if (null != result) {
            return new String(result);
        } else {
            return null;
        }
    }

    /**
     * 实名认证 3要素
     *
     * @param appId  appId
     * @param appKey appKey
     * @param name   用户名
     * @param idNO   身份证号码
     * @param phone  手机号码
     * @return
     */
    public static boolean nameAuth3(String appId, String appKey, String name, String idNO, String phone) {

        String url = "https://api.253.com/open/carriers/carriers-auth";
        Map<String, String> params = new HashMap<String, String>();
        params.put("appId", appId);
        params.put("appKey", appKey);
        params.put("name", name);
        params.put("idNum", idNO);
        params.put("mobile", phone);
        try {
            String result = HttpClientUtils.httpPost(url, params);
            System.out.println(result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String code = jsonObject.getString("code");
            if ("200000".equals(code)) {
                JSONObject data = jsonObject.getJSONObject("data");
                String tmp = data.getString("result");
                if ("01".equals(tmp)) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
        return false;

    }


    public static void main(String[] args) {
        System.out.println(sendSms("N4240117", "hh2Vywp0qn8aad", "【俱丰出行】您的验证码是5566。如非本人操作，请忽略本短信", "15079017029"));
        //System.out.println(DateTimeUtil.DateTimeToString(new Date(1579488898)));
        //nameAuthBySign("jyYxJZnw","ZunJj0jd","方旭帆","330821199411196013");
        //nameAuth3("pRdcwLDf","kzpSGkEh","吉宇林","142601199808188214","17635247932");
    }
}
